package com.tanhua.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.manager.constant.CacheKey;
import com.tanhua.manager.domain.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * 在客户端发请求到达Controller之前，先从请求头里得到token
 * 再从redis里找到token对应的Admin对象，绑定到当前线程上
 *
 * 这样的话，我们的Controller、Service里：
 *      不需要再获取请求头数据、从redis里获取数据、再转换Admin对象
 *      可以从当前线程上直接获取到当前管理员Admin对象
 * @author liuyp
 * @date 2021/02/20
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头Authorization
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            response.setStatus(401);
            return false;
        }

        //2. 截取得到token值
        String token = authorization.replace("Bearer ", "");

        //3. 从Redis里找到token对应的Admin对象
        String adminJson = redisTemplate.opsForValue().get(CacheKey.TOKEN_PREFIX + token);
        if (adminJson == null) {
            response.setStatus(401);
            return false;
        }

        //4. 把adminJson还原成Admin对象
        Admin admin = JSON.parseObject(adminJson, Admin.class);
        redisTemplate.opsForValue().set(CacheKey.TOKEN_PREFIX+token, adminJson, Duration.ofHours(1));

        //5. 绑定到当前线程上
        AdminHolder.setAdmin(admin);
        AdminHolder.setToken(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.removeToken();
        AdminHolder.removeAdmin();
    }
}
